<script setup lang="ts">
import { getStuTableAPI, deleteFileAPI } from '@/http/student'
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, UploadProps } from 'element-plus'
import { bus } from '@/utils/mitt'
import { searchTableInfoAPI } from '@/http/student/index.ts'
import { usePaginationStore } from '@/store/modules/pagination'
import userDetailDialog from '../components/userDetailDialog.vue'
import pagination from '../components/pagination.vue'

const usePaginaStore = usePaginationStore()
// userDetailDialog实例
const userDetailDialogRef = ref()
// 表格每一行的用户信息实例
const userId = ref()
// 搜索框数据绑定
const search = ref()
// 选择器数据绑定
const select = ref()
const selectName = ref()
const loading = ref(false)
const headerName = ref()
const stuData = ref()
// 获取文件表格数据
const getStuTable = async () => {
  try {
    const res = await getStuTableAPI(
      usePaginaStore.pageSize,
      usePaginaStore.currentPage,
    )
    if (res.result) {
      loading.value = false // 数据获取成功，隐藏加载效果
      stuData.value = res.result
      usePaginaStore.total = res?.total || 0
      headerName.value = res.headerTitleName
        .split(',')
        .map((header: string) => ({
          prop: header,
          label: header,
          value: header,
          align: 'center',
        }))
    } else {
      stuData.value = []
      headerName.value = []
    }
  } catch (error) {
    loading.value = false // 捕获错误时隐藏加载效果
    console.error('获取数据表时发生错误：', error)
    ElMessage.error('获取数据表时发生错误，请稍后再试。')
  }
}
// 删除文件
const deleteFile = async () => {
  if (stuData.value.length === 0)
    return ElMessage.error('没有任何数据可以删除！')
  try {
    loading.value = true // 开始删除时显示加载效果
    const res = await deleteFileAPI()
    if (res.status === 0) {
      loading.value = false // 删除成功，隐藏加载效果
      ElMessage.success(`${res.message}`)
      stuData.value = []
      headerName.value = []
      search.value = ''
      select.value = ''
      getStuTable()
    } else {
      ElMessage.error(`删除失败：${res.message}`)
    }
  } catch (error) {
    loading.value = false // 捕获错误时隐藏加载效果
    console.error('删除数据时发生错误：', error)
    ElMessage.error('删除数据时发生错误，请稍后再试。')
  }
}
// 导入成功函数
const handleSuccess = (response: any) => {
  if (response.status === 0) {
    loading.value = false
    ElMessage.success(`${response.message}`)
  } else {
    ElMessage.error(`导入失败，xls格式有误！`)
    ElMessage.error(`${response.message}`)
  }
  getStuTable()
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `当前限制上传1个文件，你选择了${files.length}个文件, 加起来总共是${
      files.length + uploadFiles.length
    }个`,
  )
}
const openUserInfo = (row: any) => {
  bus.emit('userRow', 5)
  userDetailDialogRef.value.open()
  userId.value = row
}
// 选择器查询
const selectOption = async () => {
  search.value = ''
  selectName.value = select.value
}
// 搜索框查询
const searchUser = async () => {
  if (selectName.value) {
    const res = await searchTableInfoAPI(
      search.value,
      selectName.value,
      usePaginaStore.pageSize,
      usePaginaStore.currentPage,
    )
    ElMessage.success('查询成功')
    stuData.value = res.results
    usePaginaStore.total = res?.total || 0
  }
}
const viewImpFile = () => {
  ElMessage.warning('未开发！！！')
}
onMounted(() => {
  getStuTable()
})
</script>

<template>
  <el-card>
    <div class="input-select">
      <el-input
        v-model="search"
        style="width: 240px; margin-bottom: 10px"
        size="large"
        placeholder="输入关键字进行搜索"
        :suffix-icon="Search"
        @change="searchUser"
        clearable
        :disabled="selectName ? false : true"
      />
      <el-select
        v-model="select"
        placeholder="选择列名进行查询"
        size="large"
        style="width: 240px"
        @change="selectOption"
      >
        <el-option
          v-for="(column, index) in headerName"
          :key="index"
          :label="column.label"
          :value="column.value"
        />
      </el-select>
    </div>
    <div class="upload">
      <el-upload
        class="upload-demo"
        action="http://127.0.0.1:3000/user/uploadXLSX"
        multiple
        :limit="1"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
      >
        <el-button type="primary">导入文件</el-button>
        <template #tip>
          <div class="el-upload__tip">jpg/png 文件大小不能少于 500KB.</div>
        </template>
      </el-upload>
      <div class="rightBtn">
        <el-button type="primary" @click="viewImpFile">
          查看已导入的文件
        </el-button>
        <el-popconfirm
          title="是否要删除表数据？"
          width="180"
          @confirm="deleteFile"
        >
          <template #reference>
            <el-button type="danger">删除文件</el-button>
          </template>
        </el-popconfirm>
      </div>
    </div>
    <el-table
      :data="stuData"
      v-if="stuData && stuData.length > 0"
      border
      style="width: 100%"
      v-loading="loading"
      @row-dblclick="openUserInfo"
    >
      <el-table-column
        type="index"
        fixed
        label="序号"
        width="60"
        align="center"
      />
      <el-table-column
        v-for="(column, index) in headerName"
        :key="index"
        :prop="column.prop"
        :label="column.prop"
        :align="column.align"
      />
    </el-table>
    <el-empty style="height: 100vh" description="暂无数据" v-else></el-empty>
    <pagination
      :isDelete="stuData"
      :selectName="selectName"
      :search="search"
      :searchUser="searchUser"
      :getStuTable="getStuTable"
    />
    <userDetailDialog :userDataId="userId" ref="userDetailDialogRef" />
  </el-card>
</template>

<style scoped lang="scss">
.el-card {
  // height: 100vh;
  .input-select {
    display: flex;

    .el-input {
      margin-right: 15px;
    }
  }
}

.upload {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.upload-demo {
  display: flex;
  width: 260px;
  flex-wrap: wrap;
}

body {
  margin: 0;
}

.example-showcase .el-loading-mask {
  z-index: 9;
}
</style>
